<template>
  <div class="container">
    <div class="content" v-if="isGoLogin">
      <Captcha :mobile="mobile" v-if="isGoLogin"></Captcha>
    </div>
    <div class="content" v-else>
      <Navbar></Navbar>
      <div class="register-box">
        <h2>登录/注册</h2>
        <van-cell-group inset :border="false">
          <van-field
            :border="false"
            size="large"
            v-model="mobile"
            type="number"
            name="手机号"
            label="手机号"
            placeholder="请输入手机号码"
          />
        </van-cell-group>
        <div style="margin: 28px;">
          <van-button block native-type="submit" :color="mobile ? '#3ca7fa' : 'rgba(60,167,250,.6)'" @click="mobile && getCode()">获取短信验证码</van-button>
        </div>
        <div class="login" @click="goTo('/login')">使用密码登录</div>
        <van-checkbox v-model="checked" shape="square" class="checkbox">勾选协议<a href="" v-text="'《用户协议》'"></a>和<a href="" v-text="'《隐私协议》'"></a></van-checkbox>
      </div>
      <van-dialog v-model="show" show-cancel-button @confirm="send">
        <template #default>
          <div style="display: flex;padding: 28px;">
            <van-field
              v-model="content"
              center
              placeholder="请输入图形验证码"
            >
            </van-field>
            <img v-lazy="captcha.img" style="width: 80px;height: 36px;" @click="init">
          </div>
        </template>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import Navbar from '@/components/common/Navbar';
import Captcha from '@/components/common/Captcha';
import { getImageCode, getSms } from '@/network/member';
import { Notify } from 'vant';

export default {
  components: {
    Navbar,
    Captcha,
  },
  data() {
    return {
      url: this.$route.query.url || '',
      checked: false,
      content: '',
      show: false,
      isGoLogin: false,
      mobile: '',
      captcha: {},
    };
  },
  methods: {
    send() {
      const userInfo = {
        mobile: this.mobile,
        image_captcha: this.content,
        image_key: this.captcha.key,
        scene: 'login',
      };
      getSms(userInfo);
      this.isGoLogin = true;
    },
    init() {
      getImageCode().then((res) => {
        this.captcha = res.data;
      });
    },
    getCode() {
      if (!this.checked) return Notify('请勾选协议');
      if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.mobile)) {
        return Notify({ type: 'danger', message: '请输入正确的手机号' });
      }
      this.show = true;
    },
    goTo(path) {
      this.$router.push({ path, query: { url: this.url } });
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="less" scoped>
h2 {
  font-size: 24px;
  font-weight: 400;
  margin: 28px 0 18px 28px;
}
.login {
  margin: 20px 0 40px;
  text-align: center;
  color: #3ca7fa;
}
.checkbox {
  color: rgba(0,0,0,.4);
  font-size: 12px;
  margin-left: 26px;
  a {
    font-size: 12px;
    color: #3ca7fa;
    margin: 0 8px;
  }
}
</style>
